/* eslint-disable react/display-name */
import { Button, Row, Input, Form, Space, Drawer, Table } from "antd";
import React, { useState, useRef, memo, forwardRef, useImperativeHandle, useCallback } from "react";
import { v4 as uuidv4 } from "uuid";
import { User, userList, userSave, userView } from "./userApi";
import { roleSimpleList } from "../role/roleApi";
import { TableRowSelection } from "antd/es/table/interface";
// 新增 or 编辑用户
export default memo(
	forwardRef(function FormDrawer(props: DataUpdate<User.UserDTO>, ref: any) {
		const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
		const [open, setOpen] = useState<boolean>(false);
		const [action, setAction] = useState<string>("添加");
		const [roleList, setRoleList] = useState<IdName[]>([]);
		const [form] = Form.useForm();

		useImperativeHandle(ref, () => ({
			open: async (id: string) => {
				let isEdit = false;
				setAction("添加");
				if (id) {
					isEdit = true;
					setAction("编辑");
				}
				setOpen(true);
				let res = await roleSimpleList();
				if (res.data) {
					setRoleList(res.data);
				}

				isEdit ? editUser(id) : addUser();
			},
		}));

		// 新增用户
		const addUser = () => {
			form.setFieldsValue({
				userId: uuidv4(),
				name: "",
				username: "",
				email: "",
				roleIds: [],
			});
			setSelectedRowKeys([]);
		};

		const editUser = async (id: string) => {
			console.log(id);
			let res = await userView(id);
			form.setFieldsValue(res.data);
			let arr: React.Key[] = [];
			res.data?.roleIds?.map((val) => {
				arr.push(val);
			});
			setSelectedRowKeys(arr);
		};

		// 关闭抽屉
		const onClose = () => {
			setOpen(false);
		};

		//保存
		const onOK = async () => {
			var values = await form.validateFields();
			if (values) {
				let param = form.getFieldsValue();
				let res = await userSave(param);
				if (res.data && props.update) {
					props.update(res.data);
				}
				onClose();
			}
		};

		const columns: any[] = [
			{
				title: "角色",
				dataIndex: "name",
				key: "name",
				align: "left",
			},
		];
		const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
			console.log("selectedRowKeys changed: ", newSelectedRowKeys);
			setSelectedRowKeys(newSelectedRowKeys);
			form.setFieldValue("roleIds", newSelectedRowKeys);
		};

		const rowSelection: TableRowSelection<IdName> = {
			selectedRowKeys,
			onChange: onSelectChange,
		};

		return (
			<Drawer
				title={action + "用户"}
				width={720}
				onClose={onClose}
				open={open}
				styles={{
					body: {
						paddingBottom: 80,
					},
				}}
				extra={
					<Space>
						<Button onClick={onClose}>取消</Button>
						<Button onClick={onOK} type="primary">
							提交
						</Button>
					</Space>
				}
			>
				<Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
					<Form.Item hidden name="userId" />
					<Form.Item hidden name="roleIds" />
					<Form.Item name="username" label="用户名" rules={[{ required: true, message: "请输入用户名" }]}>
						<Input placeholder="请输入用户名" />
					</Form.Item>
					<Form.Item name="name" label="姓名" rules={[{ required: true, message: "请输入姓名" }]}>
						<Input placeholder="请输入姓名" />
					</Form.Item>
					<Form.Item name="email" label="邮箱">
						<Input placeholder="请输入邮箱" />
					</Form.Item>
					<Table rowKey="id" rowSelection={rowSelection} pagination={false} columns={columns} dataSource={roleList}></Table>
				</Form>
			</Drawer>
		);
	})
);
